#pragma once
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace log_ns;
static const int gsockfd = -1;
static const uint16_t glocalport = 8888;
enum //错误码 exit的时候用
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};
// UdpServer user("192.1.1.1",8899);
class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t localport = glocalport)
        : _sockfd(gsockfd),
          _localport(glocalport),
          //_localip(localip),
          _isrunning(false)
    {
    }

    void InitServer()
    {
        // 1.创建socket套接字
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        // AF_INET:网络套接
        // SOCK_DGRAM:UDP
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success,_sockfd=%d\n", _sockfd); // 3

        // 2.绑定
        struct sockaddr_in local; // 放本地信息
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);
        // local.sin_addr.s_addr = inet_addr(_localip.c_str()); // 需要4字节ip 需要网络序列的ip
        local.sin_addr.s_addr = INADDR_ANY; // 网络地址任意 服务器端进行任意IP地址bind
        // local.sin_addr.s_addr = inet_addr("127.0.0.1");
        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof local); // 绑定
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "socket bind success\n");
    }
    void Start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            // 要知道客户端是谁
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                InetAddr addr(peer);
                // uint16_t peerport = ntohs(peer.sin_port);
                // std::string peerip = inet_ntoa(peer.sin_addr); // 把4字节的地址转化成string

                inbuffer[n] = 0;
                std::cout << "[" << addr.Ip() << ":" << addr.Port() << "]# " << inbuffer << std::endl;
                std::string echo_string = "[udp_server echo] #";
                echo_string += inbuffer;

                sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr *)&peer, len);
            }
            else
            {
                std::cout<<"recvfrom , error"<<std::endl;
            }
        }
    }
    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            ::close(_sockfd);
    }

private:
    int _sockfd;         // 文件描述符
    uint16_t _localport; // 本地端口号
    // 在云服务器中 服务器端不能bind自己的公网地址 也不能bind自己的本地地址 建议使用0作为IP地址 可以接收port的任何一个ip发来的消息
    //  std::string _localip; // ip地址
    //  ip+port=套接字（该互联网中唯一一个进程）
    //  网络通信==进程间通信

    bool _isrunning; // 状态
};